#pragma once
#include<iostream>
#include<memory>
#include"Epoller.hpp"
#include"Socket.hpp"
#include"Common.hpp"
#include"Connection.hpp"
#include"Channel.hpp"

using namespace SocketModule;

class Listener:public Connection
{
    public:
    Listener(int port=8080):_port(port),_listener(std::make_unique<TcpSocket>())
    {
        _listener->BuildTcpSocketMethod(_port);
        SetEvents(EPOLLIN | EPOLLET);
        SetNonBlock(_listener->Fd());
    }
    ~Listener(){}
    void Recver()override
    {
        InetAddr client;
        while(true)
        {
            int sockfd=_listener->Accept(&client);
            if(sockfd==ACCEPT_ERR)
            {
                break;
            }
            else if(sockfd==ACCEPT_CONTINUE)
            {
                continue;
            }
            else if(sockfd==ACCEPT_DONE)
            {
                break;
            }
            else
            {
                std::shared_ptr<Connection>conn=std::make_shared<Channel>(sockfd,client);
                conn->SetEvents(EPOLLIN||EPOLLET);
                if(_handler!=nullptr)
                {
                    conn->SetHandler(_handler);
                }
                GetOwner()->AddConnection(conn);
            }
            
        }
    }
    void Sender()override
    {}
    void Excepter()override
    {}
    int GetSockFd()override
    {
        return _listener->Fd();
    }
    private:
    int _port;
    std::unique_ptr<Socket>_listener;
};